package com.crazymaker.springcloud.base.filter;

import com.crazymaker.springcloud.common.constants.SessionConstants;
import com.crazymaker.springcloud.common.context.SessionHolder;
import com.crazymaker.springcloud.standard.redis.RedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@Component("sessionHeadNameFilter" )
public class SessionSeedFilter extends OncePerRequestFilter
{

    public SessionSeedFilter(RedisRepository redisRepository,
                             RedisOperationsSessionRepository sessionRepository)
    {
        this.redisRepository = redisRepository;
        this.sessionRepository = sessionRepository;
    }

    private RedisOperationsSessionRepository sessionRepository;

    RedisRepository redisRepository;
    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 返回true代表不执行过滤器，false代表执行
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request)
    {

        String seed = request.getHeader(SessionConstants.SESSION_SEED_HEAD);
        if (StringUtils.isNotEmpty(seed))
        {
            SessionHolder.setSessionSeed(seed);
            return false;
        }
//        seed = (String) request.getAttribute(SessionConstants.SESSION_SEED_HEAD);
//        if (StringUtils.isNotEmpty(seed))
//        {
//            SessionHolder.setSessionSeed(seed);
//            return false;
//        }
        return true;
/*

        if (request.getRequestURL().indexOf("/session/") > 0)
        {
            return true;
        }

*/

/*
        if(null== SessionHolder.getSid())
        {
            return true;
        }
*/

    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
    {

        String seed = SessionHolder.getSessionSeed();
        String sid = redisRepository.getSessionId(seed);

        if (StringUtils.isNotEmpty(sid))
        {
            Session session = sessionRepository.findById(sid);
            if (null != session)
            {
                SessionHolder.setSid(sid);
            }
        }

        chain.doFilter(request, response);
    }
}